package com.jacobson.core.framework.lifecycle

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.jacobson.core.App
import com.jacobson.core.base.IFragment
import com.jacobson.core.mvp.BaseMvpFragment
import com.jacobson.core.utils.ImmersiveExtensions
import com.jacobson.core.widget.logger.LoggerFactory
import org.simple.eventbus.EventBus
import javax.inject.Inject
import javax.inject.Singleton

/**
 * ================================================
 *  Fragment生命周期管理
 *  @author Wucz on 2018/7/19 16:28
 * ================================================
 */
@Singleton
class FragmentLifecycleImpl @Inject constructor() : FragmentManager.FragmentLifecycleCallbacks() {
    private val logger = LoggerFactory.getLogger()
    @Inject
    lateinit var app: App

    override fun onFragmentCreated(fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?) {
        logger.w("onFragmentCreated->${f.javaClass.simpleName}=${f is IFragment}")
        (f as? IFragment)?.run {
            takeIf { it.useEventBus() }?.let { /*TODO Register EventBus*/ }
            injectBundleParameter()
            if (this.useEventBus()) {
                EventBus.getDefault().register(this)
            }
            setupFragmentComponent(app.provideAppComponent())
        }
    }

    override fun onFragmentActivityCreated(fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?) {
        logger.w("onFragmentActivityCreated->${f.javaClass.simpleName}=${f is IFragment}")
        ImmersiveExtensions.fitsSystemWindows(f)
        (f as? IFragment)?.run {
            initData(savedInstanceState)
            (f as? BaseMvpFragment<*>)?.run {
                preInitData(savedInstanceState)
            }
        }
    }

    override fun onFragmentStarted(fm: FragmentManager, f: Fragment) {
        logger.w("onFragmentStarted->${f.javaClass.simpleName}=${f is IFragment}")
        super.onFragmentStarted(fm, f)
    }

    override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
        logger.w("onFragmentResumed->${f.javaClass.simpleName}=${f is IFragment}")
        super.onFragmentResumed(fm, f)
    }

    override fun onFragmentDestroyed(fm: FragmentManager, f: Fragment) {
        super.onFragmentDestroyed(fm, f)
        (f as? IFragment)?.run {
            if (useEventBus()) {
                EventBus.getDefault().unregister(this)
            }
        }
    }

}